<template>
  <div>
    <!-- <div>{{  }}：</div> -->

    <el-upload
      class="avatar-uploader"
      action=""
      accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
      :disabled="disabled"
      :show-file-list="false"
      :on-change="handleAvatarChange"
      :http-request="uploadInstallImg"
    >
      <div v-if="imageUrl" class="img-box">
        <img class="avatar" :src="imageUrl" alt="" />
        <span class="icon-box">
          <span @click="handlePictureCardPreview">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span @click="handleDownload">
            <i class="el-icon-download"></i>
          </span>
          <span @click="handleRemove">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible" :width="dialogWidth">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  props: {
    userDetail: Object
  },
  data () {
    return {
      imageUrl: '',
      dialogImageUrl: '',
      dialogWidth: '0',
      dialogVisible: false,

      disabled: false,

      imageFile: '',
      userData: {},
      sourceUrl: 'http://119.23.46.76:8080'
    }
  },
  computed: {
    ...mapState(
      {
        userInfo: state => state.user.userInfo,
        backUrl: state => state.user.backUrl
      }
    )
  },
  methods: {
    // 预览
    handlePictureCardPreview () {
      this.dialogImageUrl = this.imageUrl
      this.dialogVisible = true
    },
    // 下载
    handleDownload () {
      console.log('下载', this.imageFile)
      //   console.log(this.imageUrl);
      let hreLocal = ''
      if (this.imageUrl !== '') {
        hreLocal = this.imageUrl
        this.downloadByBlob(hreLocal, this.userData.username + 'pic')
      }
    },
    // 移除
    handleRemove () {
      this.imageUrl = ''
      setTimeout(() => {
        this.disabled = false
        console.log('移除', this.imageFile)
      }, 800)
    },
    // 文件上传变化
    async handleAvatarChange (file, filelist) {
      this.imageFile = file // 文件
      this.imageUrl = URL.createObjectURL(file.raw)
      if (this.imageUrl !== '') {
        this.disabled = true
      }
    },
    // 文件上传前校验
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 调用接口，上传文件
    async uploadInstallImg (param) {
      // console.log('图片文件信息', param);

      const formData = new FormData()
      formData.append('file', param.file)
      try {
        const { data: res } = await this.$http.post('/user/updateHead', formData, { headers: { 'Content-type': 'multipart/form-data' } })
        console.log('图片上传', res)
        if (res.code === 200) {
          setTimeout(() => {
            window.location.reload()
          }, 100)
        }
      } catch (error) {
        console.log('图片上传失败', error)
      }
    },
    setDialogWidth (that, defWidth, dialogName) {
      var val = document.body.clientWidth
      const def = parseInt(defWidth)
      if (val < def) {
        that[dialogName] = '98%'
      } else {
        that[dialogName] = def + 'px'
      }
    },

    downloadByBlob (url, name) {
      const image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.src = url
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob)
          this.download(url, name)
          // 用完释放URL对象
          URL.revokeObjectURL(url)
        })
      }
    },
    download (href, name) {
      const eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    }
  },
  async created () {
    if (this.userDetail && this.userDetail.profilePhoto !== '') {
      this.userData = this.userDetail
      this.imageUrl = this.sourceUrl + this.userDetail.profilePhoto
      if (this.imageUrl.indexOf('res') === -1) {
        const { data: res } = await this.$http.get('/user/getUser')
        // console.log('userData', res)
        if (res.code === 200) {
          this.userData = res.data
          this.imageUrl = this.sourceUrl + this.userData.profilePhoto
        }
      }
      this.disabled = true
    }
    this.setDialogWidth(this, '800', 'dialogWidth')
  },
  mounted () {
    window.addEventListener('resize', () => {
      return (() => {
        this.setDialogWidth(this, '800', 'dialogWidth')
      })()
    })
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .img-box {
    position: relative;
    width: 178px;
    height: 178px;

    .icon-box {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.5);
      transition: opacity 0.3s;
      display: flex;
      align-items: center;
      justify-content: center;
      span {
        margin: 5px;
        cursor: pointer;
      }
    }
    .icon-box:hover {
      opacity: 0.9;
      z-index: 1;
    }
  }

  @media (max-width: 576px) {
    .avatar-uploader-icon {
      width: 70px;
      height: 70px;
      line-height: 70px;
    }
    .avatar {
      width: 70px;
      height: 70px;
    }
    .img-box {
      width: 70px;
      height: 70px;
      .icon-box {
        span {
          margin: 2px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
